Popular Searches
Popular Course Categories
Popular Courses

Formatting and Parsing Date and Time Values

Formatting and Parsing Date and Time Values

Regular Expressions, Date and Time, and Utility Modules

Formatting and Parsing Date and Time Values in Python

Course: Python Training

Topic: Formatting and Parsing Date and Time Values

Course Link: Python Training Course at JustAcademy

Demo Link: Register for a Course Demo

Official Website: JustAcademy


1. Introduction to Date and Time Handling in Python

Date and time handling is an important part of Python programming. Applications frequently need to record transactions, schedule meetings, calculate deadlines, generate reports, store timestamps, process logs, and display dates in a readable format.

Python provides the built-in datetime module for creating, formatting, parsing, comparing, and manipulating date and time values. It includes classes such as date, time, datetime, timedelta, and timezone.

Two particularly important operations are:

  • Formatting: Converting a date or time object into a readable string using strftime().
  • Parsing: Converting a string containing a date or time into a Python date or time object using strptime().

For example, a Python program may receive the date 22-10-2026 from a form, convert it into a date object, perform calculations, and then display it as October 22, 2026.

Learning Objectives

  • Understand Python's date and time data types.
  • Create date, time, and datetime objects.
  • Format date and time values with strftime().
  • Parse strings with strptime().
  • Understand common date and time format directives.
  • Work with ISO 8601 date and time representations.
  • Handle invalid date strings and parsing errors.
  • Calculate durations and manipulate dates with timedelta.
  • Understand time zones and timezone-aware datetime objects.
  • Build practical date-processing applications.

2. Importing the datetime Module

The datetime module is included in Python's standard library. You do not need to install an external package to use its basic features.

Importing the Entire Module

import datetime

current_date = datetime.date.today()
print(current_date)

The output depends on the system date when the program runs.

Importing Specific Classes

from datetime import date, time, datetime, timedelta

today = date.today()
print(today)

Importing specific classes can make code shorter and easier to read. Both import styles are valid; choose one and use it consistently within a project.


3. Understanding Python Date and Time Classes

The datetime module provides different classes for representing dates, times, combined date-time values, durations, and time zones.

Class Purpose Example
date Represents a calendar date without a time. date(2026, 10, 22)
time Represents a time of day without a date. time(14, 30, 0)
datetime Combines a calendar date and a time. datetime(2026, 10, 22, 14, 30)
timedelta Represents a duration or difference between dates and times. timedelta(days=7)
timezone Represents a fixed UTC offset. timezone.utc

Example: Creating Different Objects

from datetime import date, time, datetime, timedelta

my_date = date(2026, 10, 22)
my_time = time(14, 30, 15)
my_datetime = datetime(2026, 10, 22, 14, 30, 15)
duration = timedelta(days=5)

print(my_date)
print(my_time)
print(my_datetime)
print(duration)

Output:

2026-10-22
14:30:15
2026-10-22 14:30:15
5 days, 0:00:00

These objects are useful because Python can perform date calculations and comparisons on them more reliably than on unstructured strings.


4. Understanding Date and Time Formatting

Formatting means converting a date or time object into a string that follows a specified presentation format. Python uses the strftime() method for this operation.

Basic Syntax

date_or_datetime_object.strftime(format_string)

The format string contains directives beginning with the percent character, such as %d, %m, and %Y.

Example: Formatting a Date

from datetime import date

my_date = date(2026, 10, 22)

formatted_date = my_date.strftime("%d-%m-%Y")

print(formatted_date)

Output:

22-10-2026

The format string means:

  • %d represents the day of the month.
  • %m represents the month as a number.
  • %Y represents the four-digit year.

Example: Formatting a Complete Date and Time

from datetime import datetime

event = datetime(2026, 10, 22, 14, 45, 30)

formatted = event.strftime("%d-%m-%Y %H:%M:%S")

print(formatted)

Output:

22-10-2026 14:45:30

Formatting is especially useful when displaying data to users, generating reports, exporting records, and creating readable log messages.


5. Common strftime() Format Directives

Format directives control how individual date and time components appear in a string.

Directive Meaning Example
%Y Four-digit year. 2026
%y Two-digit year. 26
%m Month as a zero-padded number. 10
%B Full month name. October
%b Abbreviated month name. Oct
%d Day of the month. 22
%A Full weekday name. Thursday
%a Abbreviated weekday name. Thu
%H Hour using the 24-hour clock. 14
%I Hour using the 12-hour clock. 02
%M Minute. 45
%S Second. 30
%f Microsecond, represented by six digits. 123456
%p AM or PM according to the locale. PM
%j Day of the year. 295
%w Weekday number, where Sunday is 0. 4
%z UTC offset, if available. +0530
%% A literal percent character. %

Some format directives depend on the platform's underlying C library, and locale-specific names may vary. Consult the official Python documentation when using less common directives.


6. Formatting Dates in Different Styles

A single date object can be displayed in many formats without changing the underlying date.

from datetime import date

today = date(2026, 10, 22)

print(today.strftime("%d-%m-%Y"))
print(today.strftime("%Y/%m/%d"))
print(today.strftime("%B %d, %Y"))
print(today.strftime("%b %d, %Y"))
print(today.strftime("%A, %d %B %Y"))

Output:

22-10-2026
2026/10/22
October 22, 2026
Oct 22, 2026
Thursday, 22 October 2026

When to Use Each Format

Format Example Typical Use
%d-%m-%Y 22-10-2026 Human-readable dates in day-month-year order.
%Y-%m-%d 2026-10-22 Consistent date representation and sorting.
%B %d, %Y October 22, 2026 Reports, documents, and user interfaces.
%a, %d %b %Y Thu, 22 Oct 2026 Compact displays and summaries.

Choose formats according to the needs of your application and audience. For machine-readable date strings, ISO-style formats such as YYYY-MM-DD help reduce ambiguity.


7. Formatting Time Values

The time class represents a time of day independently of a date. Its values can be formatted using strftime().

Example: 24-Hour Time

from datetime import time

meeting_time = time(14, 35, 20)

print(meeting_time.strftime("%H:%M:%S"))

Output:

14:35:20

Example: 12-Hour Time

from datetime import time

meeting_time = time(14, 35, 20)

print(meeting_time.strftime("%I:%M:%S %p"))

Output:

02:35:20 PM

Formatting Time Without Seconds

from datetime import time

start_time = time(9, 5)

print(start_time.strftime("%I:%M %p"))

Output:

09:05 AM

Use 24-hour formatting for schedules and system logs when clarity is important. Use 12-hour formatting when it better suits the application's audience.


8. Formatting Complete Datetime Values

A datetime object contains both a date and a time. It can be formatted using any combination of date and time directives.

from datetime import datetime

event = datetime(2026, 10, 22, 14, 45, 30)

print(event.strftime("%d-%m-%Y %H:%M"))
print(event.strftime("%A, %B %d, %Y"))
print(event.strftime("%I:%M %p on %d %b %Y"))
print(event.strftime("%Y-%m-%dT%H:%M:%S"))

Output:

22-10-2026 14:45
Thursday, October 22, 2026
02:45 PM on 22 Oct 2026
2026-10-22T14:45:30

The last example resembles the ISO 8601 date-time representation. When exchanging date-time values between systems, consider including an explicit UTC offset or using UTC where appropriate.


9. Introduction to Date and Time Parsing

Parsing converts a text string into a structured date or time object. It is useful when input comes from a form, CSV file, database export, configuration file, or external service.

Python provides strptime() methods for parsing strings into date, time, and datetime objects.

Basic Syntax

datetime.strptime(date_string, format_string)

The format string tells Python how to interpret each part of the input. The string and format must agree.

Example: Parsing a Date

from datetime import datetime

date_text = "22-10-2026"

parsed_date = datetime.strptime(date_text, "%d-%m-%Y")

print(parsed_date)
print(type(parsed_date))

Output:

2026-10-22 00:00:00
<class 'datetime.datetime'>

The parsed result is a datetime object with the time set to midnight because the input contained only a date.


10. Parsing Dates With Different Formats

The parsing format must match the order and type of the components in the input string.

from datetime import datetime

date_1 = datetime.strptime("22/10/2026", "%d/%m/%Y")
date_2 = datetime.strptime("2026-10-22", "%Y-%m-%d")
date_3 = datetime.strptime("October 22, 2026", "%B %d, %Y")
date_4 = datetime.strptime("22 Oct 2026", "%d %b %Y")

print(date_1.date())
print(date_2.date())
print(date_3.date())
print(date_4.date())

Output:

2026-10-22
2026-10-22
2026-10-22
2026-10-22

Common Parsing Formats

Input String Format String
22-10-2026 %d-%m-%Y
2026/10/22 %Y/%m/%d
10/22/2026 %m/%d/%Y
22 October 2026 %d %B %Y
Thu, 22 Oct 2026 %a, %d %b %Y

Be careful with dates such as 03/04/2026. Depending on the convention, this can mean March 4 or April 3. Define the expected format instead of guessing.


11. Parsing Time Strings

When the input contains only a time, use datetime.strptime() and extract the time component, or use time.strptime() when a time tuple is appropriate. The standard datetime.time class does not provide a strptime() class method in all Python versions; parsing through datetime.strptime() is a portable approach.

Example: Parsing a 24-Hour Time

from datetime import datetime

time_text = "14:35:20"

parsed_time = datetime.strptime(time_text, "%H:%M:%S").time()

print(parsed_time)

Output:

14:35:20

Example: Parsing a 12-Hour Time

from datetime import datetime

time_text = "02:35 PM"

parsed_time = datetime.strptime(time_text, "%I:%M %p").time()

print(parsed_time)

Output:

14:35:00

Use %I for the 12-hour clock and %p for the AM/PM marker. When parsing 12-hour input, include the AM/PM marker to avoid ambiguity.


12. Parsing Combined Date and Time Strings

Combined date-time strings contain both a calendar date and a time. These can be parsed in a single operation when the format is known.

from datetime import datetime

date_time_text = "22-10-2026 14:35:20"

parsed_datetime = datetime.strptime(
    date_time_text,
    "%d-%m-%Y %H:%M:%S"
)

print(parsed_datetime)
print("Date:", parsed_datetime.date())
print("Time:", parsed_datetime.time())

Output:

2026-10-22 14:35:20
Date: 2026-10-22
Time: 14:35:20

Parsing a Date-Time With AM/PM

from datetime import datetime

text = "October 22, 2026 at 02:35 PM"

parsed = datetime.strptime(
    text,
    "%B %d, %Y at %I:%M %p"
)

print(parsed)

Output:

2026-10-22 14:35:00

13. Understanding ISO 8601 Date and Time Formats

ISO 8601 is an international standard for representing dates and times. A common date format is YYYY-MM-DD, while a date-time may use a T separator and an optional UTC offset.

Representation Example Meaning
Date 2026-10-22 Year, month, day.
Local date-time 2026-10-22T14:35:20 Date and time without a timezone offset.
UTC date-time 2026-10-22T09:05:20+00:00 Date and time with a UTC offset of zero.
Date-time with offset 2026-10-22T14:35:20+05:30 Date and time with an offset of five hours and thirty minutes.

Parsing an ISO Date

from datetime import date

text = "2026-10-22"

parsed_date = date.fromisoformat(text)

print(parsed_date)

Output:

2026-10-22

Parsing an ISO Date-Time

from datetime import datetime

text = "2026-10-22T14:35:20"

parsed_datetime = datetime.fromisoformat(text)

print(parsed_datetime)

Output:

2026-10-22 14:35:20

The fromisoformat() methods are convenient when the input follows a supported ISO-style format. For arbitrary user-entered formats, use an explicit parser and validation rules.


14. Formatting and Parsing in One Workflow

Many applications need to parse a string, perform calculations, and format the result in a different style. This is a common workflow in reporting and data processing.

from datetime import datetime

input_text = "22/10/2026"

parsed_date = datetime.strptime(input_text, "%d/%m/%Y")

formatted_date = parsed_date.strftime("%B %d, %Y")

print("Original:", input_text)
print("Parsed:", parsed_date)
print("Formatted:", formatted_date)

Output:

Original: 22/10/2026
Parsed: 2026-10-22 00:00:00
Formatted: October 22, 2026

Step-by-Step Process

  1. Receive the input string from the user or data source.
  2. Choose the expected input format.
  3. Parse the string into a Python date or datetime object.
  4. Perform any required validation or calculation.
  5. Format the result for display or export.

15. Handling Invalid Date and Time Values

Parsing can fail when a string does not match the specified format or represents an impossible date. Python raises ValueError in such cases.

Example: Invalid Date

from datetime import datetime

date_text = "31-02-2026"

try:
    parsed_date = datetime.strptime(date_text, "%d-%m-%Y")
    print(parsed_date)
except ValueError:
    print("Invalid date entered.")

Output:

Invalid date entered.

February does not have 31 days, so the date is invalid. Handling exceptions prevents an unexpected input from terminating the program.

Creating a Reusable Date Parsing Function

from datetime import datetime

def parse_date(date_text: str, date_format: str = "%d-%m-%Y"):
    try:
        return datetime.strptime(date_text, date_format).date()
    except ValueError:
        return None

print(parse_date("22-10-2026"))
print(parse_date("31-02-2026"))

Output:

2026-10-22
None

This function returns a date object when parsing succeeds and None when the value is invalid. In larger applications, you may prefer to raise a custom exception or return a structured validation result that explains the problem.


16. Understanding Date Arithmetic With timedelta

The timedelta class represents a duration. It can be added to or subtracted from a date or datetime object to calculate future or past dates.

Adding Days

from datetime import date, timedelta

start_date = date(2026, 10, 22)

future_date = start_date + timedelta(days=7)

print(future_date)

Output:

2026-10-29

Subtracting Days

from datetime import date, timedelta

today = date(2026, 10, 22)

previous_date = today - timedelta(days=10)

print(previous_date)

Output:

2026-10-12

Calculating the Difference Between Dates

from datetime import date

start_date = date(2026, 10, 1)
end_date = date(2026, 10, 22)

difference = end_date - start_date

print(difference.days)

Output:

21

Use timedelta for elapsed durations, deadlines, expiry calculations, and date offsets. A duration of 30 days is not the same thing as one calendar month; for month-based calculations, use explicit calendar logic or an appropriate library.


17. Working With Current Date and Time

The today() and now() methods retrieve the current date or date-time according to the system's local clock unless a timezone is specified where supported.

Current Date

from datetime import date

today = date.today()

print(today)

Current Local Date and Time

from datetime import datetime

current_datetime = datetime.now()

print(current_datetime)

The actual output depends on when and where the program runs.

Current UTC Date and Time

from datetime import datetime, timezone

current_utc = datetime.now(timezone.utc)

print(current_utc)

Using an aware UTC datetime is a useful default for recording event timestamps in applications that operate across multiple time zones.


18. Naive and Timezone-Aware Datetime Objects

Python distinguishes between naive and timezone-aware datetime objects.

  • Naive datetime: Does not contain enough timezone information to identify an unambiguous instant.
  • Aware datetime: Includes timezone information that allows the instant to be interpreted relative to UTC.

Example: Naive Datetime

from datetime import datetime

local_event = datetime(2026, 10, 22, 14, 30)

print(local_event)
print(local_event.tzinfo)

Output:

2026-10-22 14:30:00
None

Example: UTC-Aware Datetime

from datetime import datetime, timezone

utc_event = datetime(
    2026, 10, 22, 14, 30,
    tzinfo=timezone.utc
)

print(utc_event)
print(utc_event.tzinfo)

Output:

2026-10-22 14:30:00+00:00
UTC

Do not assume a naive datetime is UTC or local time without an explicit application rule. When comparing instants across time zones, use aware datetime objects consistently.


19. Working With Time Zones Using zoneinfo

Python's zoneinfo module provides access to IANA time zone data on supported systems. It can represent regional time zones such as Asia/Kolkata and America/New_York, including applicable daylight-saving rules.

Example: Using the Indian Time Zone

from datetime import datetime
from zoneinfo import ZoneInfo

india_time = datetime.now(ZoneInfo("Asia/Kolkata"))

print(india_time)
print(india_time.strftime("%d-%m-%Y %I:%M:%S %p %Z"))

The output depends on the current time. The Asia/Kolkata timezone represents Indian Standard Time.

Converting an Aware Datetime to Another Time Zone

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

utc_time = datetime(
    2026, 10, 22, 9, 0,
    tzinfo=timezone.utc
)

india_time = utc_time.astimezone(ZoneInfo("Asia/Kolkata"))

print(india_time.strftime("%Y-%m-%d %H:%M:%S %Z%z"))

Output:

2026-10-22 14:30:00 IST+0530

The example converts 09:00 UTC into 14:30 in India. Use astimezone() when converting an already identified instant. Simply replacing timezone information with replace(tzinfo=...) is not a conversion operation.

Some systems may require installation of the tzdata package if IANA timezone data is not available locally.


20. Parsing Strings That Contain Timezone Offsets

A date-time string may contain a UTC offset, such as +05:30 or +00:00. Python can parse offset-aware strings with the appropriate format directive or an ISO parsing method.

Using strptime() With %z

from datetime import datetime

text = "2026-10-22 14:30:00 +0530"

parsed = datetime.strptime(
    text,
    "%Y-%m-%d %H:%M:%S %z"
)

print(parsed)
print(parsed.utcoffset())

Output:

2026-10-22 14:30:00+05:30
5:30:00

Using fromisoformat()

from datetime import datetime

text = "2026-10-22T14:30:00+05:30"

parsed = datetime.fromisoformat(text)

print(parsed)
print(parsed.utcoffset())

Output:

2026-10-22 14:30:00+05:30
5:30:00

A UTC offset identifies the difference from UTC at that time, but it does not necessarily identify the complete regional timezone rules. Use zoneinfo when the application needs a named region's timezone behavior.


21. Converting Between Time Zones

The astimezone() method converts an aware datetime to another timezone while preserving the represented instant.

from datetime import datetime
from zoneinfo import ZoneInfo

new_york = datetime(
    2026, 10, 22, 9, 0,
    tzinfo=ZoneInfo("America/New_York")
)

india = new_york.astimezone(ZoneInfo("Asia/Kolkata"))

print("New York:", new_york.strftime("%Y-%m-%d %H:%M %Z"))
print("India:", india.strftime("%Y-%m-%d %H:%M %Z"))

The resulting local times depend on the timezone rules for the specified date. The conversion preserves the instant, even when the displayed clock time changes.

Best Practices for Time Zones

  • Store event timestamps as UTC-aware values when possible.
  • Convert to the user's regional timezone for display.
  • Use named zones with zoneinfo for regional rules.
  • Avoid assuming every timezone is a whole-hour offset from UTC.
  • Be careful when scheduling events during daylight-saving transitions.

22. Comparing and Sorting Date Values

Parsed date objects can be compared directly. This is more reliable than comparing arbitrary date strings that use different formats.

from datetime import datetime

first = datetime.strptime("22-10-2026", "%d-%m-%Y")
second = datetime.strptime("30-10-2026", "%d-%m-%Y")

print(first < second)
print(first == second)
print(second - first)

Output:

True
False
8 days, 0:00:00

Sorting Date Strings

from datetime import datetime

date_strings = [
    "30-10-2026",
    "01-10-2026",
    "22-10-2026"
]

dates = [
    datetime.strptime(value, "%d-%m-%Y")
    for value in date_strings
]

sorted_dates = sorted(dates)

for value in sorted_dates:
    print(value.strftime("%d-%m-%Y"))

Output:

01-10-2026
22-10-2026
30-10-2026

For aware datetimes, compare values that represent instants using consistent timezone-aware data. Avoid comparing naive and aware datetimes directly, because Python raises a TypeError.


23. Calculating Age and Time Differences

Date calculations are common in employee records, membership systems, booking applications, and reporting dashboards. A simple difference in days can be calculated by subtracting two date objects.

Calculating Days Between Two Dates

from datetime import date

start = date(2026, 10, 1)
end = date(2026, 10, 22)

days = (end - start).days

print("Days between:", days)

Output:

Days between: 21

Calculating Age in Completed Years

from datetime import date

def calculate_age(birth_date: date, today: date) -> int:
    age = today.year - birth_date.year

    birthday_not_reached = (
        (today.month, today.day)
        < (birth_date.month, birth_date.day)
    )

    if birthday_not_reached:
        age -= 1

    return age

birth_date = date(2000, 12, 15)
reference_date = date(2026, 10, 22)

print(calculate_age(birth_date, reference_date))

Output:

25

This example calculates age in completed calendar years for ordinary birthdays. Applications that handle February 29 birthdays should define a clear policy for how anniversaries are treated in non-leap years.


24. Handling Locale and Human-Readable Dates

Locale affects the language and regional conventions used for some date and time representations. For example, the full month name or weekday name can vary by locale.

from datetime import datetime

event = datetime(2026, 10, 22, 14, 30)

print(event.strftime("%A, %d %B %Y"))
print(event.strftime("%a, %d %b %Y"))

Output in an English locale:

Thursday, 22 October 2026
Thu, 22 Oct 2026

Locale-dependent output can differ between operating systems and environments. If an application requires a specific language or regional date style, configure and test its locale behavior carefully. Avoid changing a process-wide locale unexpectedly in a multi-user application.


25. Common Errors in Date and Time Formatting

Error or Problem Cause Solution
ValueError during parsing. The input does not match the expected format or represents an invalid date. Check the input and format string; handle the exception.
Month and day are reversed. The wrong date convention was assumed. Specify the exact expected format, such as %d/%m/%Y.
Unexpected AM/PM result. The pattern uses the wrong hour directive or omits AM/PM. Use %I with %p for 12-hour input.
Wrong year output. %y was used instead of %Y. Use %Y when the full year is required.
Timezone information is missing. The input was parsed without an offset or timezone rule. Parse an offset or explicitly attach a known regional timezone when appropriate.
Unexpected difference between two timestamps. Naive and aware values or different time zones were mixed. Use consistent aware datetime values for instant-based calculations.
Unsupported format directive. The directive may not be supported by the platform's formatting library. Use widely supported directives and consult Python documentation.
Incorrect result for a month-based deadline. A fixed number of days was treated as a calendar month. Use calendar-aware date arithmetic for month-based rules.

Example: Safe Parsing With Error Handling

from datetime import datetime

def read_date(text: str):
    try:
        return datetime.strptime(text, "%Y-%m-%d").date()
    except ValueError as error:
        print(f"Please enter a valid date: {error}")
        return None

result = read_date("2026-02-30")

if result is not None:
    print("Accepted:", result)

Output:

Please enter a valid date: day is out of range for month

26. Best Practices for Formatting and Parsing Dates

  • Use datetime objects for calculations rather than manipulating date strings manually.
  • Always define the expected input format for ambiguous dates.
  • Use strftime() to format objects and strptime() to parse known string formats.
  • Use ISO 8601 representations when exchanging dates and timestamps between systems.
  • Prefer four-digit years with %Y for clarity.
  • Catch ValueError when parsing untrusted or user-entered input.
  • Use timezone-aware datetime objects when recording or comparing real-world instants.
  • Use UTC for storage when appropriate and convert to local time for presentation.
  • Use zoneinfo for regional timezones instead of assuming a fixed offset captures every rule.
  • Do not confuse a duration of 30 days with one calendar month.
  • Test leap years, month boundaries, invalid dates, and daylight-saving transitions where relevant.
  • Keep input validation, business rules, and display formatting as separate responsibilities.
  • Document the timezone and date convention expected by APIs, files, and databases.

27. Practical Project: Date and Time Formatter

This project accepts a date-time string in a specified format, parses it, displays it in multiple formats, and calculates a future date. It demonstrates common date-processing operations in a single program.

Project Requirements

  • Accept a date-time string in DD-MM-YYYY HH:MM format.
  • Parse the input into a datetime object.
  • Display the date in a long, readable format.
  • Display the time in 12-hour and 24-hour formats.
  • Calculate a date seven days later.
  • Handle invalid input gracefully.

Complete Python Code

from datetime import datetime, timedelta

def format_datetime(input_text: str) -> None:
    input_format = "%d-%m-%Y %H:%M"

    try:
        parsed = datetime.strptime(input_text, input_format)
    except ValueError:
        print("Invalid date or time.")
        print("Expected format: DD-MM-YYYY HH:MM")
        return

    print("Original:", input_text)
    print("Long date:", parsed.strftime("%A, %d %B %Y"))
    print("12-hour time:", parsed.strftime("%I:%M %p"))
    print("24-hour time:", parsed.strftime("%H:%M"))

    future = parsed + timedelta(days=7)

    print("Seven days later:", future.strftime("%d-%m-%Y %H:%M"))

user_input = "22-10-2026 14:30"

format_datetime(user_input)

Expected Output

Original: 22-10-2026 14:30
Long date: Thursday, 22 October 2026
12-hour time: 02:30 PM
24-hour time: 14:30
Seven days later: 29-10-2026 14:30

Project Explanation

  • strptime() converts the input string into a datetime object.
  • strftime() generates readable date and time strings.
  • timedelta(days=7) calculates the date and time seven days later.
  • The try-except block handles invalid dates and incorrect input formats.

Project Extension Tasks

  1. Allow users to choose between different date formats.
  2. Add an option to parse ISO 8601 timestamps.
  3. Display the weekday for the selected date.
  4. Calculate the number of days between two dates.
  5. Add timezone-aware conversion using zoneinfo.
  6. Save formatted output to a text or CSV file.

28. Practice Exercises

Beginner Exercises

  1. Create a date object for October 22, 2026, and print it as 22-10-2026.
  2. Format a datetime object using the full weekday and month names.
  3. Convert a time from 24-hour format to 12-hour format.
  4. Parse a string in DD/MM/YYYY format.
  5. Print the current date using date.today().

Intermediate Exercises

  1. Parse a combined date-time string and display the date and time separately.
  2. Convert 2026-10-22 into October 22, 2026.
  3. Calculate the date 30 days after a given date.
  4. Calculate the number of days between two dates.
  5. Write a function that catches invalid date input and returns an error message.
  6. Parse a timestamp containing a UTC offset.

Advanced Exercises

  1. Build a date formatter that supports multiple user-selected formats.
  2. Create a deadline calculator that checks whether a date is in the past.
  3. Convert an aware datetime from UTC to Asia/Kolkata.
  4. Build a log processor that parses timestamps from log entries.
  5. Create a meeting scheduler that displays one event in two regional time zones.
  6. Test a date-handling function with leap years, invalid dates, and month-end values.

29. Interview Questions and Answers

Q1. What is the datetime module in Python?

Answer: It is a standard-library module that provides classes and methods for working with dates, times, durations, and timezones.

Q2. What is the difference between strftime() and strptime()?

Answer: strftime() converts a date or time object into a formatted string. strptime() parses a string into a date-time object using a specified format.

Q3. What does %Y represent?

Answer: It represents the year using four digits, such as 2026.

Q4. What is the difference between %H and %I?

Answer: %H represents the hour using the 24-hour clock, while %I represents the hour using the 12-hour clock.

Q5. Why does strptime() require a format string?

Answer: The format string tells Python how to interpret the input's components and separators.

Q6. What happens if a date string is invalid?

Answer: Parsing normally raises ValueError. Programs should validate input and handle the exception when necessary.

Q7. What is timedelta?

Answer: timedelta represents a duration that can be used for date-time arithmetic and calculating differences.

Q8. What is ISO 8601?

Answer: It is an international standard for representing dates and times. A common date representation is YYYY-MM-DD.

Q9. What is the difference between naive and aware datetime objects?

Answer: A naive datetime lacks timezone information sufficient to identify an unambiguous instant. An aware datetime has timezone information that makes it interpretable relative to UTC.

Q10. How can you get the current UTC time?

Answer: Use datetime.now(timezone.utc) to obtain the current UTC date and time as an aware datetime.

Q11. How do you convert a datetime to another timezone?

Answer: Use astimezone() with an appropriate timezone, such as one obtained from zoneinfo.ZoneInfo, on an aware datetime.

Q12. Why should date strings not always be compared directly?

Answer: Different string formats may order their components differently. Parsing into date or datetime objects allows chronological comparisons.

Q13. Can Python calculate the difference between two dates?

Answer: Yes. Subtracting two date or compatible datetime objects returns a timedelta representing their difference.

Q14. Is 30 days always equal to one month?

Answer: No. Calendar months have different lengths, so month-based calculations require calendar-aware logic.

Q15. Why are timezones important in applications?

Answer: Timezones ensure that timestamps and scheduled events are interpreted correctly across regions, especially when applications operate internationally or handle daylight-saving changes.


30. Quick Revision Checklist

  • Import date and time classes from Python's datetime module.
  • Use date for dates, time for times, and datetime for combined values.
  • Use strftime() to format date and time objects.
  • Use strptime() to parse strings with a known format.
  • Remember that %d is the day, %m is the month, and %Y is the four-digit year.
  • Use %H for 24-hour time and %I with %p for 12-hour time.
  • Use fromisoformat() for supported ISO-style date and time strings.
  • Handle invalid input with appropriate exception handling.
  • Use timedelta for durations and date arithmetic.
  • Use aware datetime objects for timezone-sensitive instants.
  • Use zoneinfo for named regional timezone rules.
  • Use astimezone() to convert an aware datetime to another timezone.
  • Test leap years, invalid dates, and ambiguous input formats.
  • Keep parsing, validation, calculations, and display formatting separate.

31. Conclusion

Formatting and parsing date and time values are essential skills for Python developers. The datetime module allows applications to convert text into structured values, present dates in readable formats, calculate time differences, and work with timezone-aware timestamps.

Use strftime() when displaying or exporting date-time values, and strptime() when converting known input formats into Python objects. For more reliable applications, validate input, document date conventions, and use explicit timezone handling whenever timestamps represent real-world events.

Additional Learning Resources

whatsapp